// import qqmapwx from "../../qqmap-wx-jssdk.min"
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    sat:0,
    delall:false,
    Intervals:[],
    setInterval:[],
    currentTimeStamp:0,
    longitude:0,
    latitude:0,
    m1:0,//偏移的距离
    s1:0,//定位位置距离设定位置的距离
    m2:0,//偏移的距离
    s2:0,//定位位置距离设定位置的距离
    m3:0,//偏移的距离
    s3:0,//定位位置距离设定位置的距离
    m4:0,//偏移的距离
    s4:0,//定位位置距离设定位置的距离
    circles: [],
    markers:[],
    jwlvalue1:[],
    jwlvalue2:[],
    jwlvalue3:[],
    jwlvalue4:[],
    cwlvalue1:[],
    cwlvalue2:[],
    cwlvalue3:[],
    cwlvalue4:[],
    intervalId1: null,  
    intervalId2: null,  
    intervalId3: null,  
    intervalId4: null,  
    spxx:"",
    num:[],
    name:[],
    everynum:"",
    everyName:"",
    list:{},
    img:"",
    number11:[100,300,500,1000],
    index1:0,
    show:0,
    coordinate:[],
    device:"",
    zong:"显示单个老人",
    jhrname:"",
    jhrage:"",
  },
  onLoad: function () {
    let currentTimeStamp = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8)
    this.setData({
      currentTimeStamp: currentTimeStamp
    });
    // 导航栏
    // 1.获取屏幕可使用宽度
    let windowWidth = wx.getSystemInfoSync().windowWidth;
    // 2.获取状态栏高度
    const statusBarHeight = wx.getSystemInfoSync().statusBarHeight;
    //3.获取胶囊按钮位置信息
    const menuButton = wx.getMenuButtonBoundingClientRect();
    this.setData({
      navtop:menuButton.top
    }) 
  },
  onShow:function(){
    this.stopTimer1()
    this.stopTimer2()
    this.stopTimer3()
    this.stopTimer4()
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
      mask: true 
    });
    this.setData({      
      num:[],
      name:[],
    })
    this.getDate1()
    this.getProfile()
  },
  onReady(){
    this.mapCtx = wx.createMapContext('map')
  },
  //点击获取点击位置的坐标，圆形
  getgps(e){
    // 获取点击位置的经纬度
    if(this.data.circles.length === 0){
      const newLatitude = e.detail.latitude;
      const newLongitude = e.detail.longitude;
      wx.request({
        url: 'https://dj.ifankui.com/api/device/addWeilan',
        method:'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data:{
          device_code:this.data.everynum,
          zuobiao:newLongitude + "," + newLatitude,
          size:this.data.show
        },
        success:(res)=>{
          console.log(res);
          console.log(this.data.num);
          wx.request({
            url: 'https://dj.ifankui.com/api/device/getWeilan',
            method:'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data:{
              device_code:this.data.everynum,
            },
            success:(res)=>{
              console.log(res);
              const newLatitude = res.data.weilan[0].zuobiao.split(",")[1];
              const newLongitude =res.data.weilan[0].zuobiao.split(",")[0];
              console.log(newLatitude,newLongitude);
              // 创建新的圆形标记对象
              const newCircle = {
                latitude: newLatitude,
                longitude: newLongitude,
                color: '#FF4500DD',
                radius: res.data.weilan[0].size, // 半径
                fillColor: '#00FF0055'
              };
              // 创建新的标记对象
              const newMarker = {
                id: res.data.weilan[0].id, // 使用当前时间戳作为标记的唯一 ID
                latitude: newLatitude,
                longitude: newLongitude,
                iconPath: '../../images/positioning.png', // 替换为你的标记图标路径
                width: 20,
                height: 30,
                type: 'new',
                callout: {
                  content: '家', // 标记内容
                  color: '#000000', 
                  fontSize: 14, 
                  borderRadius: 5, 
                  bgColor: '#ffffff', 
                  padding: 5,
                  display: 'ALWAYS' // 始终显示文字标签
                }
              };
              // 将新的圆形标记和标记对象添加到数据中
              this.data.circles.push(newCircle)
              // 更新数据
              this.setData({
                circles: this.data.circles,
                list: res.data.weilan
              });
            }
          })
        }
      })
    }
    
  },
  //获取坐标
  getDate1(){
    const that = this
    const app =getApp()
    this.setData({
      openid:app.globalData.openid,
      circles:[],
      delall:false,
      markers:[],
      num:[],
      name:[],
      list:{},
      zong:"显示单个老人",
    })
    //获取设备列表
    wx.request({
      url: 'https://dj.ifankui.com/api/usrEn/deviceList',
      method:"POST",
      data:{
        openid:this.data.openid
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success:(res)=>{
        console.log(res);
        for(let i=0;i<res.data.data.length;i++){
          this.data.num.push(res.data.data[i].device_code);
          this.data.name.push(res.data.data[i].xm)
        }
        const newnum = this.data.num
        const newname = this.data.name
        console.log(newname);
        this.setData({
          num:newnum,
          name:newname,
        },()=>{
          //获取设备坐标
          for(let i=0;i<this.data.num.length;i++){
            wx.request({
              url: 'https://dj.ifankui.com/api/device/getDeviceInfo',
              method:"POST",
              data:{
                openid:this.data.openid,
                device_code:this.data.num[i],
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              success:(res)=>{
                console.log(res);
                const loc1 = res.data.device.last_position[0].loc.split(",")[0]
                const loc2 = res.data.device.last_position[0].loc.split(",")[1]
                var initialMarker = {
                  id: i,
                  latitude: loc2,
                  longitude: loc1,
                  iconPath: '../../images/blue2.png', // 蓝色定位标记的图标路径
                  width: 20,
                  height: 20,
                  type: 'initial', // 类型为初始定位标记
                  callout: {
                    content: this.data.name[i], // 标记内容
                    color: '#000000', 
                    fontSize: 14, 
                    borderRadius: 5, 
                    bgColor: '#ffffff', 
                    padding: 5,
                    display: 'ALWAYS' // 始终显示文字标签
                  }
                };
                this.data.markers.push(initialMarker)
                this.setData({
                    latitude:loc2,
                    longitude:loc1,
                    markers: this.data.markers
                })
                console.log(this.data.markers);
                this.getDate2(i)
              }
            })  
          }
        })
        this.getValue1()
        this.getValue2()
        this.getValue3()
        this.getValue4()
      }
    })
  },
  getDate2(i){
          //获得电子围栏
          wx.request({
            url: 'https://dj.ifankui.com/api/device/getWeilan',
            method:"POST",
            data:{
              device_code:this.data.num[i]
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success:(res)=>{
              console.log(res);
              const newLatitude = res.data.weilan[0].zuobiao.split(",")[1];
              const newLongitude =res.data.weilan[0].zuobiao.split(",")[0];
              // 创建新的圆形标记对象
              const newCircle = {
                latitude: newLatitude,
                longitude: newLongitude,
                color: '#FF4500DD',
                radius: res.data.weilan[0].size, // 半径
                fillColor: '#00FF0055'
              };
              // 创建新的标记对象
              
              // 将新的圆形标记和标记对象添加到数据中
              this.data.circles.push(newCircle);
              // 更新数据
              this.setData({
                circles: this.data.circles,
                list:res.data.weilan,
                sat:this.data.circles.length,
                show:res.data.weilan[0].size
              });
              console.log(this.data.circles);
            }
          })
        
  },
  //单个老人
  getDate3(){
    const device = this.data.device
    const that = this
    const app =getApp()
    this.setData({
      openid:app.globalData.openid,
      circles:[],
      name:[],
      num:[],
      delall:true,
      list:{},
      markers:[],
      everynum:device
    })
    wx.request({
      url: 'https://dj.ifankui.com/api/device/getDeviceInfo',
      method:"POST",
      data:{
        openid:this.data.openid,
        device_code:this.data.device,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success:(res)=>{
        const loc1 = res.data.device.last_position[0].loc.split(",")[0]
        const loc2 = res.data.device.last_position[0].loc.split(",")[1]
        console.log(this.data.everyName);
        var initialMarker = {
          id: 0,
          latitude: loc2,
          longitude: loc1,
          iconPath: '../../images/blue2.png', // 蓝色定位标记的图标路径
          width: 20,
          height: 20,
          type: 'initial', // 类型为初始定位标记
          callout: {
            content: this.data.everyName, // 标记内容
            color: '#000000', 
            fontSize: 14, 
            borderRadius: 5, 
            bgColor: '#ffffff', 
            padding: 5,
            display: 'ALWAYS' // 始终显示文字标签
          }
        };
      this.data.markers.push(initialMarker)
      this.setData({
        latitude:loc2,
        longitude:loc1,
        markers: this.data.markers
        },()=>{
          //获取设备列表
          wx.request({
            url: 'https://dj.ifankui.com/api/usrEn/deviceList',
            method:"POST",
            data:{
              openid:this.data.openid
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success:(res)=>{
                console.log(res);
              for(let i=0;i<res.data.data.length;i++){
                this.data.num.push(res.data.data[i].device_code);
                this.data.name.push(res.data.data[i].xm)
              }
              const newnum = this.data.num
              const newname = this.data.name
              
              this.setData({
                num:newnum,
                name:newname
              })
              console.log(this.data.num);
              //获取电子围栏
              wx.request({
                url: 'https://dj.ifankui.com/api/device/getWeilan',
                method:"POST",
                data:{
                  device_code:device
                },
                header: {
                  "Content-Type": "application/x-www-form-urlencoded"
                },
                success:(res)=>{
                  const newLatitude = res.data.weilan[0].zuobiao.split(",")[1];
                  const newLongitude =res.data.weilan[0].zuobiao.split(",")[0];
                  console.log(newLatitude,newLongitude);
                  // 创建新的圆形标记对象
                  const newCircle = {
                    latitude: newLatitude,
                    longitude: newLongitude,
                    color: '#FF4500DD',
                    radius: res.data.weilan[0].size, // 半径
                    fillColor: '#00FF0055'
                  };
                  // 创建新的标记对象
                  const newMarker = {
                    id: res.data.weilan[0].id, // 使用当前时间戳作为标记的唯一 ID
                    latitude: newLatitude,
                    longitude: newLongitude,
                    iconPath: '../../images/positioning.png', // 替换为你的标记图标路径
                    width: 20,
                    height: 30,
                    type: 'new',
                    callout: {
                      content: '家', // 标记内容
                      color: '#000000', 
                      fontSize: 14, 
                      borderRadius: 5, 
                      bgColor: '#ffffff', 
                      padding: 5,
                      display: 'ALWAYS' // 始终显示文字标签
                    }
                  };
                  // 将新的圆形标记和标记对象添加到数据中
                  this.data.circles.push(newCircle)
                  // 更新数据
                  this.setData({
                    show:res.data.weilan[0].size,
                    circles: this.data.circles,
                    list: res.data.weilan
                  });
                  console.log(this.data.markers);
                  console.log(this.data.circles);
                  console.log(this.data.name);
                }
              })    
            }
          })
      })
      }
    }) 
    
  },
  getValue1(){
    if(this.data.num.length >= 1){
      if (this.data.intervalId1) {
        clearInterval(this.data.intervalId1);
      }
      const intervalId1 = setInterval(() => {
        wx.request({
          url: 'https://dj.ifankui.com/api/device/getWeilanAlarm',
          method:'POST',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data:{
            device_code:this.data.num[0],
          },
          success:(res)=>{
            console.log(res);
            this.setData({
                jwlvalue1:[],
                cwlvalue1:[]
            })
            for(let i=0;i<=res.data.data.length-1;i++){
              //转化字符串
              if(res.data.data[i].dt == "进围栏"){
                const hour = res.data.data[i].dt
                const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                let newvalue = {
                    hour:hour,
                    dance:dance,
                }
                this.data.jwlvalue1.unshift(newvalue)
                let arr = this.data.jwlvalue1.slice(0,1)
                this.setData({
                  jwlvalue1:arr
                })
                }else if(res.data.data[i].dt == "出围栏"){
                const hour = res.data.data[i].dt
                const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                let newvalue = {
                    hour:hour,
                    dance:dance,
                }
                this.data.cwlvalue1.unshift(newvalue)
                let arr = this.data.cwlvalue1.slice(0,1)
                this.setData({
                    cwlvalue1:arr
                })
                }
            }
          }
        })
      }, 10000);
      this.setData({
        intervalId1: intervalId1
      });
    }
  },
  getValue2(){
    if(this.data.num.length >=2){
      if (this.data.intervalId2) {
        clearInterval(this.data.intervalId2);
      }
      const intervalId2 = setInterval(() => {
        wx.request({
            url: 'https://dj.ifankui.com/api/device/getWeilanAlarm',
            method:'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data:{
              device_code:this.data.num[1],
            },
            success:(res)=>{
              console.log(res);
              this.setData({
                  jwlvalue2:[],
                  cwlvalue2:[]
              })
              for(let i=0;i<=res.data.data.length-1;i++){
                //转化字符串
                if(res.data.data[i].dt == "进围栏"){
                  const hour = res.data.data[i].dt
                  const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                  let newvalue = {
                      hour:hour,
                      dance:dance,
                  }
                  this.data.jwlvalue2.unshift(newvalue)
                  let arr = this.data.jwlvalue2.slice(0,1)
                  this.setData({
                    jwlvalue2:arr
                  })
                  }else if(res.data.data[i].dt == "出围栏"){
                  const hour = res.data.data[i].dt
                  const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                  let newvalue = {
                      hour:hour,
                      dance:dance,
                  }
                  this.data.cwlvalue2.unshift(newvalue)
                  let arr = this.data.cwlvalue2.slice(0,1)
                  this.setData({
                      cwlvalue2:arr
                  })
                  }
              }
            }
          })
      }, 10000);
      this.setData({
        intervalId2: intervalId2
      });
    }
  },
  getValue3(){
    if(this.data.num.length >=3){
      if (this.data.intervalId3) {
        clearInterval(this.data.intervalId3);
      }
      const intervalId3 = setInterval(() => {
        wx.request({
          url: 'https://dj.ifankui.com/api/device/getWeilanAlarm',
          method:'POST',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data:{
            device_code:this.data.num[2],
          },
          success:(res)=>{
            console.log(res);
            this.setData({
                jwlvalue3:[],
                cwlvalue3:[]
            })
            for(let i=0;i<=res.data.data.length-1;i++){
              //转化字符串
              if(res.data.data[i].dt == "进围栏"){
                const hour = res.data.data[i].dt
                const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                let newvalue = {
                    hour:hour,
                    dance:dance,
                }
                this.data.jwlvalue3.unshift(newvalue)
                let arr = this.data.jwlvalue3.slice(0,1)
                this.setData({
                  jwlvalue3:arr
                })
                }else if(res.data.data[i].dt == "出围栏"){
                const hour = res.data.data[i].dt
                const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                let newvalue = {
                    hour:hour,
                    dance:dance,
                }
                this.data.cwlvalue3.unshift(newvalue)
                let arr = this.data.cwlvalue3.slice(0,1)
                this.setData({
                    cwlvalue3:arr
                })
                }
            }
          }
        })
      }, 10000);
      this.setData({
        intervalId3: intervalId3
      });
    }
  },
  getValue4(){
    if(this.data.num.length ==4){
      if (this.data.intervalId4) {
        clearInterval(this.data.intervalId4);
      }
      const intervalId4 = setInterval(() => {
        wx.request({
            url: 'https://dj.ifankui.com/api/device/getWeilanAlarm',
            method:'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data:{
              device_code:this.data.num[3],
            },
            success:(res)=>{
              console.log(res);
              this.setData({
                  jwlvalue4:[],
                  cwlvalue4:[]
              })
              for(let i=0;i<=res.data.data.length-1;i++){
                //转化字符串
                if(res.data.data[i].dt == "进围栏"){
                  const hour = res.data.data[i].dt
                  const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                  let newvalue = {
                      hour:hour,
                      dance:dance,
                  }
                  this.data.jwlvalue4.unshift(newvalue)
                  let arr = this.data.jwlvalue4.slice(0,1)
                  this.setData({
                    jwlvalue4:arr
                  })
                  }else if(res.data.data[i].dt == "出围栏"){
                  const hour = res.data.data[i].dt
                  const dance = res.data.data[i]['FROM_UNIXTIME(dt)']
                  let newvalue = {
                      hour:hour,
                      dance:dance,
                  }
                  this.data.cwlvalue4.unshift(newvalue)
                  let arr = this.data.cwlvalue4.slice(0,1)
                  this.setData({
                      cwlvalue4:arr
                  })
                  }
              }
            }
          })
      }, 10000);
      this.setData({
        intervalId4: intervalId4
      });
    }
  },
  stopTimer1() {
    if (this.data.intervalId1) {
      clearInterval(this.data.intervalId1);
      this.setData({
        intervalId1: null  // 清除定时器ID
      });
      console.log("Timer stopped");
    }
  },
  stopTimer2() {
    if (this.data.intervalId2) {
      clearInterval(this.data.intervalId2);
      this.setData({
        intervalId2: null  // 清除定时器ID
      });
      console.log("Timer stopped");
    }
  },
  stopTimer3() {
    if (this.data.intervalId3) {
      clearInterval(this.data.intervalId3);
      this.setData({
        intervalId3: null  // 清除定时器ID
      });
      console.log("Timer stopped");
    }
  },
  stopTimer4() {
    if (this.data.intervalId4) {
      clearInterval(this.data.intervalId4);
      this.setData({
        intervalId4: null  // 清除定时器ID
      });
      console.log("Timer stopped");
    }
  },
  delall(){
    console.log(this.data.list);
    const app =getApp()
    const that =this
    for(let i=0;i<this.data.list.length;i++){
      wx.request({
        url: 'https://dj.ifankui.com/api/device/delWeilan',
        method:'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data:{
          device_code:this.data.list[i].device_code,
          idstr:this.data.list[i].id,
        },
        success:(res)=>{
          console.log(res);
          for(let i=1;i<this.data.markers.length;i++){
            this.data.markers.pop()
          }
          this.data.markers.splice(1)
          this.setData({
            markers:this.data.markers,
            circles:[],
            value1:[],
            value2:[],
            value3:[],
            value4:[],
            setInterval:[],
          },()=>{
            that.data.Intervals.forEach(interval => clearInterval(interval));
            that.setData({
              Intervals: []
            });
            that.data.Intervals.forEach(interval => clearInterval(interval));
            that.setData({
              Intervals: []
            });
          })
        }
      })
    }
  },
  getProfile(){
    const that = this
    const app =getApp()
    wx.request({
      url: 'https://dj.ifankui.com/api/usrEn/getProfile',
      method:'POST',
      data:{
        openid:app.globalData.openid,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success:(res)=>{
        console.log(res);
        const birthDate = res.data.data.sfz.substring(6, 14)
        const year = parseInt(birthDate.substring(0, 4), 10);
        const month = parseInt(birthDate.substring(4, 6), 10);
        const day = parseInt(birthDate.substring(6, 8), 10);
        const today = new Date();
        let age = today.getFullYear() - year;
        that.setData({
          img:res.data.data.headimg,
          jhrname:res.data.data.realname,
          jhrage:age
        })
      }
    })
  },
  showActionSheet() {
    const that = this
    wx.showActionSheet({
      itemList: ['100','300','500','1000'],
      success(res) {
        console.log(res.tapIndex) // 用户点击的按钮序号，从0开始
        that.setData({
          index1:res.tapIndex,
          show:that.data.number11[res.tapIndex]
        },()=>{
          console.log(that.data.index1,that.data.show);
        })
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  bindDateChangelaoren(e) {
    const index = e.detail.value; // 获取选择的索引
    const selectedDevice = this.data.num[index]; // 获取设备代码
    const selecteName = this.data.name[index]
    this.setData({
      device: selectedDevice,
      everyName:selecteName,
      // every:
    }, () => {
      this.getDate3();
    });
  },
})

